package com.hcj.example.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

@Configuration
public class OAuth2ServerConfig {
    private static final String DEMO_RESOURCE_ID = "api";


    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    //配置api访问控制，必须认证过后才可以访问
                    .antMatchers("/api/**").authenticated()
                    .and()
                    .authorizeRequests()
                    .antMatchers("/test/select").access("#oauth2.hasScope('select') and hasAuthority('oauth2')")
                    .antMatchers("/test/all").access("#oauth2.hasScope('all')")
                    .antMatchers("/test/read").access("#oauth2.hasScope('read')")
                    .antMatchers("/test/write").access("#oauth2.hasScope('write')");
        }
    }


    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        AuthenticationManager authenticationManager;
        @Autowired
        RedisConnectionFactory redisConnectionFactory;
        @Autowired
        DataSource dataSource;

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

//            clients.inMemory()
            // 客户端模式
//                    .withClient("client-id")
//                    .secret("client-secret")
//                    .resourceIds(DEMO_RESOURCE_ID)
//                    .authorizedGrantTypes("client_credentials", "refresh_token")
//                    .scopes("all", "select", "read", "write")
//                    .authorities("oauth2")
//                    .accessTokenValiditySeconds(20)
//                    .refreshTokenValiditySeconds(3600 * 24 * 30); //30天过期


            // 密码模式的客户端
//                    .and().withClient("client_2")
//                    .resourceIds(DEMO_RESOURCE_ID)
//                    .authorizedGrantTypes("password", "refresh_token")
//                    .scopes("select")
//                    .authorities("oauth2")
//                    .secret(finalSecret);
            // 这一块可以持久化到数据库【参考数据库脚本：oauth_client_details.sql】
            clients.jdbc(dataSource);
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
            System.out.println("默认的提交方式：" + endpoints.getAllowedTokenEndpointRequestMethods());

            endpoints
                    // 缓存到redis中
                    //.tokenStore(new RedisTokenStore(redisConnectionFactory))
                    // 缓存到内存中
                    //.tokenStore(new InMemoryTokenStore())
                    // 缓存到mysql中【参考数据库脚本：oauth_access_token.sql】
                    .tokenStore(new JdbcTokenStore(dataSource))
                    .authenticationManager(authenticationManager)
                    .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                    .reuseRefreshTokens(true);

            System.out.println("修改后的提交方式：" + endpoints.getAllowedTokenEndpointRequestMethods());
        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) {

            oauthServer
                    .tokenKeyAccess("permitAll()")
                    .checkTokenAccess("isAuthenticated()")
                    //允许表单认证
                    .allowFormAuthenticationForClients();
        }

    }
}
